package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.dao.TargetsCategoryDao;
import com.powerunion.datacollection.model.TargetsCategory;
import com.powerunion.datacollection.model.jsonObject.TreeNode;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameterSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;

public class TargetsCategoryDaoImpl extends JdbcBase implements TargetsCategoryDao { 
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			TargetsCategoryDaoImpl.class);
	
	public boolean delete(String[] codes) {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "delete");
		}
		String sql = "delete from dc_targets_category where id = ? ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		
		for(int i=0;i<codes.length;i++) {
			SqlParameterSet spSet = new SqlParameterSet();
			spSet.addParameter(new SqlParameter(SqlType.VARCHAR,codes[i]));
			update.addBatchParameter(spSet);
		}
		
		update.access();
		int[] effectCount = update.getBatchEffectCounts();
		if(effectCount != null && effectCount.length>0) {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + Constants.DELETE + "指标类别信息"
						+ Constants.SUCCESS);
			}
			return true;
		}else{
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + Constants.DELETE + "指标类别信息"
						+ Constants.FAIL);
			}
			return false;
		}
	
	}

	public String save(TargetsCategory tc){
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "save");
		}
		String sql = "";
		String resultId = "";
		if (tc.getId() == null || tc.getId().equals("") || tc.getId().indexOf("xnode")>=0) {//新增
			String id = String.valueOf(this.getSeq("dc_targets_category"));
			tc.setId(id);
			StringBuffer sqlSave = new StringBuffer();
			sqlSave.append("insert into dc_targets_category (para_seq,category_name,id) values(?,?,?)");
			sql = sqlSave.toString();
		} else {//修改
			StringBuffer sqlUpdate = new StringBuffer();
			sqlUpdate.append("update dc_targets_category set para_seq = ?, category_name = ? where id =?");
			sql = sqlUpdate.toString();
		}

		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.addParameter(new SqlParameter(SqlType.VARCHAR,tc.getParaId()));
		update.addParameter(new SqlParameter(SqlType.VARCHAR,tc.getCategoryName()));
		update.addParameter(new SqlParameter(SqlType.VARCHAR,tc.getId()));
		update.access();
		int effectCount = update.getEffectCounts();
		if(effectCount > 0) {
			
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "指标类别信息"
						+ Constants.SUCCESS);
			}
			resultId = tc.getId();
			return resultId;
		}else{
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "指标类别信息"
						+ Constants.FAIL);
			}
			return "";
		}
	
	}
	
	public TargetsCategory getBykey(String id) {
		TargetsCategory tc = new TargetsCategory();
		StringBuffer sql = new StringBuffer();
		sql.append("select id,para_seq,category_name from dc_targets_category where id = ?");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR,id));
		query.access();
		if(query.resultSetAvailable()) {//检查结果集是否可用
			//获取并处理记录集
			RsDataSet rs = new RsDataSet(query.getSqlResultSet());
			if(rs.rowCount > 0) {
				tc.setId(rs.getFieldValueAsString("id"));
				tc.setParaId(rs.getFieldValueAsString("para_seq"));
				tc.setCategoryName(rs.getFieldValueAsString("category_name"));
			}
			rs.clearAll();
		}
		return tc;
	}
	
	public JSONArray getTree(String paraSeq,int flag) throws Exception {
		logger.info(Constants.INTOMETHOD + "getTree");
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List treeNodeArray = null;
		String sqlString = "";
		if (paraSeq == null || paraSeq.equals("null")) {
			sqlString = "select id,para_seq,category_name,ordr_no from dc_item_category where para_seq is null and category_type=4 order by ordr_no";
		} else {
			sqlString = "select id,para_seq,category_name,ordr_no from dc_item_category where para_seq ='" + paraSeq
					+ "' and category_type=4 order by ordr_no";
		}
		try {
			conn = this.getConnection();
			ps = conn.prepareStatement(sqlString);
			rs = ps.executeQuery();
			treeNodeArray = new ArrayList();

			while (rs.next()) {

				TreeNode treeNode = new TreeNode();
				treeNode.setId(rs.getString("id"));
				treeNode.setText(rs.getString("category_name"));
				treeNode.setType("0");
				treeNode.setExpandable(false);
				treeNode.setLeaf(true);

				if (this.IsHasChildren(rs.getString("id"), conn) > 0) { // 父节点
					treeNode.setLeaf(false);
				}else if (flag == 0) {
					if (this.IsHasTargetChildren(rs.getString("id"), conn) > 0) {// 子节点
						treeNode.setLeaf(false);
					}
					treeNode.setType("1");
				}
				treeNodeArray.add(treeNode);
				}
			// 得到JSON数组
			JSONArray jsonarr = JSONArray.fromObject(treeNodeArray);
			logger.debug("===============treeNodeArray.size():"
					+ treeNodeArray.size() + "========================");
			logger.debug("===============targets tree:" + jsonarr
					+ "========================");
			logger.debug(Constants.SEARCH + "targets tree" + Constants.SUCCESS);
			// 返回JSON数据
			return jsonarr;
		} catch (Exception e) {
			logger.error("getTree() of throws : ", e);
			throw new Exception(Constants.SEARCH + "targets tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps, conn);
		}
	}
	
	private int IsHasChildren(String parentId,Connection conn) throws Exception {
		String sql = "";
		int total = 0;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			sql = "select count(*) from dc_item_category where para_seq=? ";
			ps = conn.prepareStatement(sql);
			ps.setString(1, parentId);

			rs = ps.executeQuery();

			if(rs.next()) {
				total = rs.getInt(1);
			}
			
		} catch (Exception e) {
			logger.error("IsHasChildren:" + Constants.SEARCH
					+ "target category children" + Constants.FAIL);
			logger.error("IsHasChildren() of throws : ", e);
			throw new Exception("IsHasChildren:" + Constants.SEARCH
					+ "target category children" + Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}

		return total;
	}
	
	private int IsHasTargetChildren(String parentId,Connection conn) throws Exception {
		String sql = "";
		int total = 0;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			sql = "select count(*) from dc_target where targets_category_id=? ";
			ps = conn.prepareStatement(sql);
			ps.setString(1, parentId);

			rs = ps.executeQuery();

			if(rs.next()) {
				total = rs.getInt(1);
			}
			
		} catch (Exception e) {
			logger.error("IsHasTargetChildren:" + Constants.SEARCH
					+ "targets children" + Constants.FAIL);
			logger.error("IsHasTargetChildren() of throws : ", e);
			throw new Exception("IsHasTargetChildren:" + Constants.SEARCH
					+ "targets children" + Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}

		return total;
	}



}
